package edu.towson.forensics.securephone;

/*** Register a Broadcast receiver inside AndroidManifest based on USB connection.
 *   This broadcast starts Service by using implicit intent.
 *   stop all instance of service by receiving USB unconnected.
 */

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class UsbBroadcastReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub

		/** Check the existing service in the list of running services on ActivityManager.
		 *  if service could find as running service will send intent to stop all instance of 
		 *  service by calling SecurePhoneConnection.stopSecurePhoneService and passing existing 
		*/
	    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) 
	    	{
	        	if ("edu.towson.forensics.securephone.SecurePhoneConnection".equals(service.service.getClassName()))
	        			SecurePhoneConnection.stopSecurePhoneService(context);
	    	}
	
	    /** Start service by using a broadcast to service and pass hostPostNo as signature that 
	     * broadcastReceiver start service 
	     */		
		if (intent.getAction().matches("android.intent.action.UMS_CONNECTED"))
			context.startService(new Intent()
								.setAction("edu.towson.forensics.securephone.action")
								.addCategory("edu.towson.forensics.securephone.category")
								.putExtra("BroadcastReceivedTime", System.currentTimeMillis())
								.putExtra("hostIpOrName", "BroadcastReceiver").putExtra("hostPortNo", "0"));		
	}
}
